﻿using System;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Notoric.Gui.Converters
{
    /// <summary>
    /// Converts a <see cref="ViewModel.Elements.Resource"/> instance to <see cref="ImageSource"/>.
    /// </summary>
    [ValueConversion(typeof(ViewModel.Elements.Resource), typeof(ImageSource))]
    public class ResourceToImageSourceConverter : IValueConverter
    {
        #region IValueConverter Members

        /// <inheritdoc/>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is ViewModel.Elements.Resource)
            {
                BitmapDecoder decoder = null;
                var imageFile = (ViewModel.Elements.Resource)value;

                switch (imageFile.Extension.ToLower())
                {
                    case ".bmp":
                        decoder = new BmpBitmapDecoder(imageFile.InputStream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                        break;
                    case ".jpg":
                    case ".jpeg":
                        decoder = new JpegBitmapDecoder(imageFile.InputStream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                        break;
                    case ".gif":
                        decoder = new GifBitmapDecoder(imageFile.InputStream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                        break;
                    case ".png":
                        decoder = new PngBitmapDecoder(imageFile.InputStream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                        break;
                    case ".tif":
                        decoder = new TiffBitmapDecoder(imageFile.InputStream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                        break;
                    case ".wdp":
                        decoder = new TiffBitmapDecoder(imageFile.InputStream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                        break;
                    case ".ico":
                        decoder = new IconBitmapDecoder(imageFile.InputStream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                        break;
                }

                return decoder.Frames[0];
            }
            else
                return null;
        }

        /// <inheritdoc/>
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
